var marker;
var map;
var geocoder;
var index = -1;
var info_windows = {};
var markers = {};

window.onload = function() { initialize(); }

function popup(new_index) {
    if (index >= 0)
        info_windows[index].close();
    else if (map.getZoom() < 14)
        map.setZoom(14);
    info_windows[new_index].open(map, markers[new_index]);
    index = new_index;
}

function addWaypoint(i, data, type) {
    var image;
    var contentString = '';
    var prefix = '<div id="map_popup">';
    var postfix = '<a class="positioning" onclick="position_marker' + data[0] + ';return false;" href="#">定位到这里</a></div>';
    if (type == "start") {
        image = new google.maps.MarkerImage('/static/img/icon_start.png',
            new google.maps.Size(25, 34),
            new google.maps.Point(0, 0),
            new google.maps.Point(12, 30));
        contentString = prefix + '<p class="start">行程起点</p>' + postfix;
    } else if (type == "photo") {
        image = new google.maps.MarkerImage('/static/img/icon_photo.png',
            new google.maps.Size(25, 34),
            new google.maps.Point(0, 0),
            new google.maps.Point(12, 30));
        contentString = prefix + '<a href="#wp' + data[2] + '"><img width="200" height="150" src="' + data[1] + '" /></a>' + postfix;
        $('#wp' + data[2]).attr('lat', data[0].lat())
        $('#wp' + data[2]).attr('lng', data[0].lng())
    } else if (type == "text") {
        image = new google.maps.MarkerImage('/static/img/icon_text.png',
            new google.maps.Size(25, 34),
            new google.maps.Point(0, 0),
            new google.maps.Point(12, 30));
        contentString = prefix + '<a class="text" href="#wp' + data[2] + '">"' + data[1] + '"</a>' + postfix;
        $('#wp' + data[2]).attr('lat', data[0].lat())
        $('#wp' + data[2]).attr('lng', data[0].lng())
    }

    var marker = new google.maps.Marker({
        position: data[0],
        map: map,
        icon: image
    });
    markers[i] = marker;

    var infowindow = new google.maps.InfoWindow({
        content: contentString
    });
    info_windows[i] = infowindow;

    google.maps.event.addListener(marker, 'click', function() {
        popup(i);
    });
}

function getData(point) {
    var items = point.children();
    var lat = parseFloat($(items[0]).text());
    var lon = parseFloat($(items[1]).text());
    var content = $(items[2]).text();
    var wp_id = null;
    if (items.length > 3)
        wp_id = $(items[3]).text();
    return [new google.maps.LatLng(lat, lon), content, wp_id];
}

function initialize() {
    var options = {
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map"), options);
    var lat = $('#map').attr('lat');
    var lng = $('#map').attr('lng');
    var center_lat = $('#map').attr('map_lat');
    var center_lng = $('#map').attr('map_lng');
    if (lat && lng) {
        lat = parseFloat(lat);
        lng = parseFloat(lng);
    } else if ($('#map_data').length > 0) {
        var points = $('#map_data').children();
        var coordinates = [];
        var latlngbounds = new google.maps.LatLngBounds();
        for (var i = 0; i < points.length; i++) {
            var point = $(points[i]);
            var type = point.attr('class');
            data = getData(point);
            if (type != 'track')
                addWaypoint(i, data, type);
            coordinates.push(data[0]);
            latlngbounds.extend(data[0]);
        }

        var path = new google.maps.Polyline({
            path: coordinates,
            strokeColor: "#0695f8",
            strokeOpacity: 1.0,
            strokeWeight: 4
        });

        if (points.length == 1)
            map.setCenter(coordinates[0]);
        else {
            if (!lat && !lng && !center_lat && !center_lng)
                map.fitBounds(latlngbounds);
            path.setMap(map);
        }
    }

    geocoder = new google.maps.Geocoder();
    if (lat && lng) {
        var latlng = new google.maps.LatLng(lat, lng);
        map.setCenter(latlng);
        marker = new google.maps.Marker({
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: latlng,
            map: map
        });
        google.maps.event.addListener(marker, 'dragend', update_position);
    } else if (center_lat && center_lng)
        map.setCenter(new google.maps.LatLng(center_lat, center_lng));
    else {
        map.setCenter(new google.maps.LatLng(39.90526746, 116.40767049));
        map.setZoom(2);
    }
    google.maps.event.addListener(map, 'click', function(event) {
        position_marker(event.latLng.lat(), event.latLng.lng());
    });
}

function position_marker(lat, lng) {
    if (marker)
        marker.setMap(null);

    marker = new google.maps.Marker({
        draggable: true,
        animation: google.maps.Animation.DROP,
        position: new google.maps.LatLng(lat, lng), 
        map: map
    });
    update_position();
    google.maps.event.addListener(marker, 'dragend', update_position);
}

function update_position() {
    var latlng = marker.getPosition();
    $('#latitude').val(latlng.lat());
    $('#longitude').val(latlng.lng());
}

function search_address() {
    var address = $('#pos_search input').val();
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            if (map.getZoom() < 14)
                map.setZoom(14);
        } else {
            alert("未找到相关位置，修改搜索条件再试试？");
        }
    });
}

$(document).ready(function(){
    $.datepicker.regional['zh-CN'] = {
        closeText: '关闭',
        prevText: '&#x3c;上月',
        nextText: '下月&#x3e;',
        currentText: '今天',
        monthNames: ['一月','二月','三月','四月','五月','六月',
        '七月','八月','九月','十月','十一月','十二月'],
        monthNamesShort: ['一','二','三','四','五','六',
        '七','八','九','十','十一','十二'],
        dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
        dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
        dayNamesMin: ['日','一','二','三','四','五','六'],
        weekHeader: '周',
        dateFormat: 'yy-mm-dd',
        firstDay: 1,
        isRTL: false,
        showMonthAfterYear: true,
        yearSuffix: '年'};
    $.datepicker.setDefaults($.datepicker.regional['zh-CN']);
    $("input.date").datepicker({
        yearRange: "-20:+0",
        changeYear: true
    });

    $('#pos_search a').click(function() { search_address(); return false; });

    $('#pos_search input').keydown(function(e) {
        var code = e.which;
        if (code == 13) e.preventDefault();
        if (code == 32 || code == 13 || code == 188 || code == 186) {
            search_address();
        }
    });

    $('#ignore_pos').change(function() {
        if($('#ignore_pos').is(":checked")) {
            $(".map-mask").show();
        } else {
            $(".map-mask").hide();
        }
    });

    $('#btn_submit').click(function() {
        if (!$('#upload').val() && $('#use_exif').prop('checked')) {
            alert('您没有选择要上传的照片，无法取得照片拍摄时间。请选择“指定时间”，或选择上传照片。');
            return;
        }

        $(this).css('opacity', 0.3);
        var lat = $('#latitude').val();
        var lng = $('#longitude').val();
        if (lat && lng) {
            var latlng = new google.maps.LatLng(lat, lng);
            geocoder.geocode({'latLng': latlng}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[0] && results[0].address_components) {
                        var country_code, province, city;
                        for (var i in results[0].address_components)
                            if ($.inArray('country', results[0].address_components[i].types) >= 0)
                                country_code = results[0].address_components[i].short_name
                            else if ($.inArray('administrative_area_level_1', results[0].address_components[i].types) >= 0)
                                province = results[0].address_components[i].long_name
                            else if ($.inArray('locality', results[0].address_components[i].types) >= 0)
                                city = results[0].address_components[i].long_name
                        if (country_code) $('#country').val(country_code);
                        if (province) $('#province').val(province);
                        if (city) $('#city').val(city);
                        $('#edit_form').submit();
                    }
                } else
                    $('#edit_form').submit();
            });
        } else
            $('#edit_form').submit();
    });

    if ($('#prompt').text()) {
        $('#prompt').css('left', (900 - $('#prompt').width()) / 2);
        $('#prompt').show().delay(10000).fadeOut();
    }

    $("img.photo").show().lazyload({
        effect: "fadeIn",
        threshold: 100
    });

});
